import ffi from 'ffi-napi';
import ref from 'ref-napi';
import path from 'path';

function sleep(time){
  return new Promise((resove,reject) =>{
    setTimeout(() =>{
      resove();
    },time);
  })
}

async function composeVoice(){
  const dll=path.join(__static,'libs/aisound_online.dll');
  const pChar=ref.refType(ref.types.CString);
  const pInt=ref.refType(ref.types.int);
  const pViod=ref.refType(ref.types.void);
  const libm = ffi.Library(dll, {
    'MSPLogin': ['int',[pChar,pChar,pChar]],
    'QTTSSessionBegin': [ pChar, [ pChar,pInt ] ],
    'QTTSTextPut':['int',[pChar,pChar,'int',pChar]],
    'QTTSAudioGet':[pViod,[pChar,pInt,pInt,pInt]],
    'QTTSSessionEnd':['int',[pChar,pChar]],
    //'MSPLogout':['int',[]]
  });
  let ret=libm.MSPLogin(null,null,ref.allocCString("appid = 618de54d"));
  console.log('MSPLogin:',ret);
  if(ret!=0){
    console.log(`MSPLogin failed, error code is: ${ret}`);
    return -1;
  }

  //let stringBuf=ref.allocCString('engine_type = local, voice_name=xiaoyan, tts_res_path =fo|res\\tts\\xiaoyan.jet;fo|res\\tts\\common.jet, sample_rate = 16000');
  let stringBuf=ref.allocCString('engine_type = cloud, voice_name=xiaoyan, sample_rate = 16000');
  let intBuf=ref.alloc(ref.types.int,0);
  let sessionBuf=ref.refType(ref.types.CString);
  sessionBuf=libm.QTTSSessionBegin(stringBuf,intBuf);
  console.log('QTTSSessionBegin:',ref.deref(intBuf));
  if(ref.deref(intBuf)!=0){
    console.log(`QTTSSessionBegin failed, error code is: ${ref.deref(intBuf)}`);
    return -1;
  }

  ret=libm.QTTSTextPut(sessionBuf,ref.allocCString('hello word'),11,null);
  console.log('QTTSTextPut:',ret);
  if(ret!=0){
    console.log(`QTTSTextPut failed, error code is: ${ret}`);
    return -1;
  }

  let data=ref.alloc(ref.types.void),len=ref.alloc(ref.types.int,1024),stat=ref.alloc(ref.types.int,0),err=ref.alloc(ref.types.int,0);
  while(1){
    data=libm.QTTSAudioGet(sessionBuf,len,stat,err);
    console.log('QTTSAudioGet:',ref.deref(len),ref.deref(stat),ref.deref(err));
    if(data!=null){
      console.log('data: ',ref.deref(data));
    }else{
      await sleep(1000);
    }
    if(ref.deref(err)!=0||ref.deref(stat)==2){
      break;
    }
  }

  ret=libm.QTTSSessionEnd(sessionBuf,"normal end");
  if(ret!=0){
    console.log(`QTTSSessionEnd failed, error code is: ${ret}`);
    return -1;
  }
  return 0;
}

function testDll(){
  const dll=path.join(__static,'libs/testDll.dll');
  const libm = ffi.Library(dll, {
    'fibonacci_init': [ 'int', [ 'int','int' ] ],
    'fibonacci_next':['int',[]],
    'fibonacci_current':['int',[]],
    'fibonacci_index':['int',[]],
  });
  libm.fibonacci_init(1,1);
  libm.fibonacci_next()
  libm.fibonacci_next()
  libm.fibonacci_next()
  libm.fibonacci_next()
  libm.fibonacci_next()
  console.log(libm.fibonacci_current())
  console.log(libm.fibonacci_index())
}

export {
  composeVoice,testDll
}